package com.zerui.manager.app.access.auth.task;

import com.zerui.manager.access.auth.task.domain.AuthTaskDetail;
import com.zerui.manager.access.auth.task.gateway.AuthTaskGateway;
import com.zerui.manager.accessauthorization.gateway.AccessAuthGateWay;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class AuthTaskSchedule {

    @Resource
    private AuthTaskGateway authTaskGateway;
    @Resource
    private AccessAuthGateWay accessAuthGateWay;

    //@Scheduled(fixedRate = 5000) 此处代码要废弃，该部门功能放置在 新增
    public void sync() {
        List<AuthTaskDetail> tasks = authTaskGateway.getUnSyncTasks();
        log.info("sync auth. size:{}", tasks.size());
        for (AuthTaskDetail task : tasks) { // 遍历下发权限的任务
            String requestId;
            if (task.getOperate() == 0) {
                // 添加
                requestId = this.accessAuthGateWay.addDistribute(Collections.singletonList(task.getDeviceId()), Collections.singleton(task.getPersonnelId()), task.getAccessAuthId());
            } else if (task.getOperate() == 1) {
                // 删除
                requestId = this.accessAuthGateWay.delDistribute(Collections.singletonList(task.getDeviceId()), Collections.singleton(task.getPersonnelId()));
            } else {
                requestId = null;
            }
            task.setRequestId(requestId);
            this.authTaskGateway.syncIng(task);
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
